<?php 
session_start();
// 检查是否登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php?redirect=settings.php');
    exit;
}

include 'config.php';

// 创建uploads目录（如果不存在）
if (!file_exists('uploads')) {
    mkdir('uploads', 0777, true);
}

$message = '';
$messageType = '';

// 获取当前设置
$stmt = $pdo->query("SELECT * FROM aiwz_settings LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // 处理文字内容
        $footerText = $_POST['footer_text'];
        
        // 处理二维码图片上传
        $qrcodeImage = $settings['qrcode_image']; // 默认使用现有图片
        
        if (isset($_FILES['qrcode_image']) && $_FILES['qrcode_image']['error'] === UPLOAD_ERR_OK) {
            $fileInfo = pathinfo($_FILES['qrcode_image']['name']);
            $extension = strtolower($fileInfo['extension']);
            
            // 允许的图片格式
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($extension, $allowedExtensions)) {
                // 生成唯一文件名
                $newFileName = uniqid() . '.' . $extension;
                $uploadPath = 'uploads/' . $newFileName;
                
                // 移动上传文件
                if (move_uploaded_file($_FILES['qrcode_image']['tmp_name'], $uploadPath)) {
                    // 删除旧图片
                    if (!empty($settings['qrcode_image']) && file_exists('uploads/' . $settings['qrcode_image'])) {
                        unlink('uploads/' . $settings['qrcode_image']);
                    }
                    $qrcodeImage = $newFileName;
                } else {
                    throw new Exception('图片上传失败');
                }
            } else {
                throw new Exception('不支持的图片格式，仅允许jpg、jpeg、png、gif');
            }
        }
        
        // 更新数据库
        $stmt = $pdo->prepare("UPDATE aiwz_settings SET footer_text = :footer_text, qrcode_image = :qrcode_image WHERE id = :id");
        $stmt->bindParam(':footer_text', $footerText);
        $stmt->bindParam(':qrcode_image', $qrcodeImage);
        $stmt->bindParam(':id', $settings['id']);
        $stmt->execute();
        
        $message = '设置更新成功';
        $messageType = 'success';
        
        // 更新当前设置变量
        $settings['footer_text'] = $footerText;
        $settings['qrcode_image'] = $qrcodeImage;
    } catch(PDOException $e) {
        $message = '数据库错误: ' . $e->getMessage();
        $messageType = 'danger';
    } catch(Exception $e) {
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网站设置 - Markdown博客</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>
        .qrcode-preview {
            max-width: 200px;
            margin: 15px 0;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
        <div class="container">
            <a class="navbar-brand" href="index.php">Markdown博客</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="create.php">发布文章</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="settings.php">设置</a>
                    </li>
                </ul>
                <div class="dropdown">
                    <button class="btn btn-outline-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <?php echo htmlspecialchars($_SESSION['username']); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="logout.php">退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <h1 class="mb-4">网站设置</h1>
                
                <?php if (!empty($message)): ?>
                    <div class="alert alert-<?php echo $messageType; ?>">
                        <?php echo $message; ?>
                    </div>
                <?php endif; ?>
                
                <form method="post" enctype="multipart/form-data">
                    <div class="card mb-4">
                        <div class="card-header">
                            文章底部统一内容设置
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="footer_text" class="form-label">底部文字内容</label>
                                <textarea class="form-control" id="footer_text" name="footer_text" rows="4" required><?php echo htmlspecialchars($settings['footer_text']); ?></textarea>
                                <div class="form-text">这段文字将显示在所有文章的底部</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="qrcode_image" class="form-label">赞助二维码图片</label>
                                <input class="form-control" type="file" id="qrcode_image" name="qrcode_image" accept="image/*">
                                <div class="form-text">上传一张二维码图片，将显示在所有文章底部的文字下方</div>
                                
                                <?php if (!empty($settings['qrcode_image']) && file_exists('uploads/' . $settings['qrcode_image'])): ?>
                                    <div>
                                        <p class="mt-2">当前图片：</p>
                                        <img src="uploads/<?php echo htmlspecialchars($settings['qrcode_image']); ?>" alt="当前二维码" class="qrcode-preview img-thumbnail">
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">保存设置</button>
                    <a href="index.php" class="btn btn-outline-secondary ms-2">返回首页</a>
                </form>
            </div>
        </div>
    </div>

    <footer class="bg-dark text-white mt-5 py-4">
        <div class="container text-center">
            <p>&copy; <?php echo date('Y'); ?> Markdown博客 - 用技术记录生活</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
